<template>
  <div>
    <van-nav-bar title="地址信息" left-text="返回" @click-left="to()" />
    <!-- 好友信息 -->
    <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认信息"
      @add="onAdd"
      @edit="onEdit"
      add-button-text="添加地址"
    />
    <!-- 新增 或 修改 好友信息 -->
    <van-popup v-model="show" position="bottom" :style="{ height: '60%' }">
      <van-address-edit
        :area-list="areaList"
        :show-delete="showDelete"
        show-set-default
        show-search-result
        :search-result="searchResult"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDelete"
        :address-info="addressInfo"
      />
    </van-popup>
  </div>
</template>

<script>
import { areaList } from "@vant/area-data"

export default {
  data() {
    return {
      // 选择地址
      chosenAddressId: "0",
      // 地址列表
      list: [],
      // 新增地址
      show: false,
      // 是否显示删除按钮
      showDelete: true,

      areaList,
      searchResult: [],
      addressInfo: {},
      address: {},
    }
  },
  mounted() {
    let token = localStorage.getItem("token")

    // 获取用户地址
    this.$get(`/v1/userAddress/userAddress`, token).then(res => {
      this.list = res.data.data
      // console.log(this.list)
      if (this.list != undefined) {
        // 添加id
        this.list.forEach((item, index) => {
          this.list[index].id = this.list[index].aid
        })
      }
    })
  },
  methods: {
    to() {
      this.$router.go(-1)
    },
    // 编辑好友
    onEdit(item) {
      this.show = true
      this.showDelete = true
      this.addressInfo = item
    },
    // 新增好友
    onAdd() {
      this.show = true
      this.showDelete = false
      this.isSave = true
      this.addressInfo = {}
    },

    // 添加修改地址
    onSave(item) {
      let token = localStorage.getItem("token")
      item.token = token

      // 详细地址
      item.address =
        item.province + item.city + item.county + item.addressDetail

      // 判断是否有默认
      if (item.isDefault == null) {
        item.isDefault = false
      } else if (item.isDefault == true) {
        this.$get(`/v1/userAddress/isDef`, token).then(res => {
          // location.reload()
        })
      }

      // 添加修改
      this.$get(`/v1/userAddress/adduser`, item).then(res => {
        // console.log(res, item)
        location.reload()
      })

      this.show = false
    },
    // 删除地址
    onDelete(item) {
      let id = item.aid
      this.$get(`/v1/userAddress/del?aid=${id}`).then(res => {
        // console.log(res)
        location.reload()
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
